{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-08-18T14:59:58.507262Z",
     "start_time": "2025-08-18T14:59:53.337725Z"
    }
   },
   "source": [
    "\n",
    "from langchain_openai import ChatOpenAI\n",
    "import os\n",
    "chat_model = ChatOpenAI(\n",
    "    # 若没有配置环境变量，请用百炼API Key将下行替换为：api_key=\"sk-xxx\",\n",
    "    api_key=os.getenv(\"DASH_SCOPE_API_KEY\"), # 如何获取API Key：https://help.aliyun.com/zh/model-studio/developer-reference/get-api-key\n",
    "    base_url=\"https://dashscope.aliyuncs.com/compatible-mode/v1\",\n",
    "    model=\"qwen-plus\",\n",
    "    temperature=0.8,\n",
    "    max_tokens=60,\n",
    ")\n",
    "\n",
    "template = \"\"\"Based on the user question, provide an Action and Action Input for what step should be taken.\n",
    "{format_instructions}\n",
    "Question: {query}\n",
    "Response:\"\"\"\n",
    "\n",
    "# 定义一个Pydantic数据格式，这个格式描述了一个\"行动\"类及其属性\n",
    "from pydantic import BaseModel, Field\n",
    "class Action(BaseModel):\n",
    "    action: str = Field(description=\"action to take\")\n",
    "    action_input: str = Field(description=\"input to the action\")\n",
    "\n",
    "# 使用Pydantic格式Action来初始化一个输出解析器\n",
    "from langchain.output_parsers import PydanticOutputParser\n",
    "parser = PydanticOutputParser(pydantic_object=Action)\n",
    "\n",
    "# 定义一个提示模板，它将用于向模型提问\n",
    "from langchain.prompts import PromptTemplate\n",
    "prompt = PromptTemplate(\n",
    "    template=\"Answer the user query.\\n{format_instructions}\\n{query}\\n\",\n",
    "    input_variables=[\"query\"],\n",
    "    partial_variables={\"format_instructions\": parser.get_format_instructions()},\n",
    ")\n",
    "prompt_value = prompt.format_prompt(query=\"What are the colors of Orchid?\")\n",
    "\n",
    "# 定义一个错误格式的字符串\n",
    "bad_response = '{\"action\": \"search\"}'\n",
    "# parser.parse(bad_response) # 如果直接解析，它会引发一个错误\n",
    "\n",
    "\n",
    "# 尝试用OutputFixingParser来解决这个问题\n",
    "from langchain.output_parsers import OutputFixingParser\n",
    "\n",
    "fix_parser = OutputFixingParser.from_llm(parser=parser, llm=chat_model)\n",
    "parse_result = fix_parser.parse(bad_response)\n",
    "print('OutputFixingParser的parse结果:',parse_result)\n",
    "\n",
    "# 初始化RetryWithErrorOutputParser，它会尝试再次提问来得到一个正确的输出\n",
    "from langchain.output_parsers import RetryWithErrorOutputParser\n",
    "retry_parser = RetryWithErrorOutputParser.from_llm(\n",
    "    parser=parser, llm=chat_model\n",
    ")\n",
    "parse_result = retry_parser.parse_with_prompt(bad_response, prompt_value)\n",
    "print('RetryWithErrorOutputParser的parse结果:',parse_result)"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "OutputFixingParser的parse结果: action='search' action_input='example query'\n",
      "RetryWithErrorOutputParser的parse结果: action='search' action_input='Orchid colors'\n"
     ]
    }
   ],
   "execution_count": 1
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
